let mandatoryMode = false;

document.addEventListener('DOMContentLoaded', function () {
    console.log('脚本正在执行...');
    chrome.storage.local.get(['mandatoryMode'], function (result) {
        mandatoryMode = result.mandatoryMode;
        console.log('强制模式：' + (result.mandatoryMode ? '开启' : '关闭'));
    });
});
//接收到的课程数据
var ContentByCourseCodeData = null, CourseCodeIDArrs = [];
let selectionZyh = '', isNext = false;
let SuccessCount = 1;
var ListData = null;

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {

    switch (msg.cmd) {
        case 'open':
            let ul = document.getElementsByClassName('ant-tabs-tabpane-active')[0].children[1];
            let oneli = ul.children;
            let totalindex = -1;
            for (let index = 0; index < oneli.length; index++) {
                let li = oneli[index];

                let isOpen = li.className.indexOf('close') !== -1;
                if (!isOpen) {
                    continue;
                }
                totalindex++;
                setTimeout(() => {
                    li.children[1].click()
                    if (index == oneli.length - 1) {
                        sendMsg('Notice', '列表展开完成');
                        finishingList();
                    }
                }, 500 * totalindex);
            }
            break;
        case 'getContentByCourseCode':
            let pcontent = JSON.parse(msg.data);
            ContentByCourseCodeData = {};
            CourseCodeIDArrs = [];
            let dataArr = pcontent.code == 0 && pcontent.data;
            for (let i = 0; i < dataArr.length; i++) {
                let data = dataArr[i];
                let children = data.children;
                if (!children) continue;
                if (!ContentByCourseCodeData[i]) {
                    ContentByCourseCodeData[i] = {};
                }
                for (let j = 0; j < children.length; j++) {
                    let aSingle = children[j];
                    ContentByCourseCodeData[i][j] = aSingle;
                    aSingle.contentType == '视频' && CourseCodeIDArrs.push(aSingle.contentCode);
                }
            }
            console.dir("数据获取成功:", ContentByCourseCodeData, CourseCodeIDArrs);
            break;
        case 'getContentStatusByCourseCode':
            let data = JSON.parse(msg.data);
            let resultArr = data.code == 0 && data.data;
            let stateArr = ['98%', '99%', '100%', '已完成'];
            resultArr[0] && console.log('获取视频播放状态：' + resultArr[0].status);

            let isComplete = resultArr[0] && stateArr.indexOf(resultArr[0].status) >= 0;
            if ((isComplete || mandatoryMode) && !isNext) {
                AutoNext();
            }
            break;
        case 'getContentStatusByCourseCode_req':
            if (!selectionZyh) {
                msg && msg.data && (selectionZyh = msg.data);
            }
            sendMsg('Notice', '当前视频编号：' + selectionZyh);
            break;
        case 'next':
            AutoNext();
            break;
        case 'notice_mandatoryMode':
            mandatoryMode = msg.data;
            chrome.storage.local.set({ mandatoryMode: msg.data }, function () {
                console.log('Value is set to ' + msg.data);
            });
            console.log('强制模式：' + (msg.data ? '开启' : '关闭'));
            break;
        default:
            break;
    }
});


function finishingList() {
    ListData = {};
    let OneLi = document.getElementsByClassName('ant-tabs-tabpane-active')[0].children[1].children;
    for (let i = 0; i < OneLi.length; i++) {
        let TwoLi = OneLi[i].children[2] && OneLi[i].children[2].children;
        if (!TwoLi) continue;
        for (let j = 0; j < TwoLi.length; j++) {
            let data = ContentByCourseCodeData[i][j];
            TwoLi[j]['setData'] = data;
            // TwoLi[j].children[1].children[1].children[0].innerHTML += '(id:' + data.contentCode + ')';
            ListData[data.contentCode] = TwoLi[j];
        }
    }
    console.table(ListData);
}

function AutoNext() {
    if (!selectionZyh || !ListData || !CourseCodeIDArrs.length) {
        console.error('数据未获取到！！！请关闭 "开发者工具" 按照使用简介再操作');
        return;
    }
    console.warn('1.即将播放下一个');
    let sub = CourseCodeIDArrs.indexOf(selectionZyh);

    do {
        selectionZyh = CourseCodeIDArrs[++sub];
    } while (selectionZyh && (!ListData[selectionZyh] || selectionZyh.indexOf('test') >= 0));

    if (!selectionZyh) {
        console.error('播放结束！！！！');
        return;
    }
    console.warn('2.获取到下一个视频id为' + selectionZyh);

    //暂时处理
    isNext = true;
    setTimeout(() => {
        console.warn('isNext为false');
        isNext = false;
    }, 20000);

    let setData = ListData[selectionZyh]['setData'];
    if (setData.contentType == '视频' && setData.status !== '已完成') {
        setTimeout(() => {
            console.info('3.自动播放成功', '已经连续播放' + (SuccessCount++) + '次数啦');
            ListData[selectionZyh].children[1].children[1].children[0].children[0].click();
        }, 3000);
    }
}

function sendMsg(cmd, data) {
    chrome.runtime.sendMessage({ cmd: cmd, data: data }, null);
}

// export type CourseCodeData22 = {

//     contentCode: "0819021001"
//     contentType: "视频"
//     contentTypeCode: "01"
//     dataType: "课件"
//     isChildren: "1"
//     kjlx: "001"
//     lastPosition: "1754.007767"
//     pid: "08190201"
//     status: "已完成"
//     title: "第1讲 软件定义、特征"
//     url: "081902/h/0819021001.mp4"
// }

